package com.etone.autotesting.socketservice.impl;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import com.etone.ejb.core.util.PropertiesUtil;

public class SocketService {

	private final static Logger logger = Logger.getLogger(SocketService.class.getName());

	private Channel channels;

	/**
 * 
 */
	public void startNettyService() {
		// Configure the server.
		ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

		// Set up the pipeline factory.
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline(new NettyServerHandler());
			}
		});
		bootstrap.setOption("child.tcpNoDelay", true);  
        bootstrap.setOption("child.keepAlive", true);  
		// Bind and start to accept incoming connections.
		String nettyPort = PropertiesUtil.getInstance().getValue("nettyPort");
		String nettyIP = PropertiesUtil.getInstance().getValue("nettyIP");
		// Bind and start to accept incoming connections.
		channels = bootstrap.bind(new InetSocketAddress(nettyIP, Integer.valueOf(nettyPort)));
		logger.info("SYSTEM||Netty(" + nettyIP + "," + nettyPort + ")启动成功！");
	}

	/**
 * 
 */
	public void stopNettyService() {
		if (channels != null)
			channels.close();
	}
}
